import dagre from 'dagre'

const autoLayout = (nodes, edges) => {
  const g = new dagre.graphlib.Graph()
  g.setGraph({ rankdir: 'LR', nodesep: 50, ranksep: 80 })
  g.setDefaultEdgeLabel(() => ({}))

  // 动态计算节点高度
  function getNodeHeight(node) {
    let baseHeight = 180 //基础节点高度
    let jobHeight = 37 //每个岗位高度25及下方外边距7
    let jobsCount = Array.isArray(node.data?.jobs) ? node.data.jobs.length : 0
    return baseHeight + jobsCount * jobHeight
  }

  nodes.forEach((node) => {
    g.setNode(node.id, { width: 200, height: getNodeHeight(node) })
  })

  edges.forEach((edge) => {
    g.setEdge(edge.source, edge.target)
  })

  dagre.layout(g)

  return nodes.map((node) => {
    const coord = g.node(node.id)
    return { ...node, x: coord.x, y: coord.y }
  })
}

export { autoLayout }
